package com.jdb.social.provider.service.impl;

import com.github.wenhao.jpa.Specifications;
import com.guns21.data.domain.JpaPageResult;
import com.guns21.result.domain.PageResult;
import com.guns21.result.domain.Result;
import com.guns21.support.service.BaseQueryService;
import com.jdb.social.api.dto.FavoriteDTO;
import com.jdb.social.controller.assembler.FavoriteAssembler;
import com.jdb.social.provider.entity.FavoriteDO;
import com.jdb.social.provider.repository.FavoriteRepository;
import com.jdb.social.provider.service.FavoriteQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class FavoriteQueryServiceImpl extends BaseQueryService implements FavoriteQueryService {

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Override
    public PageResult<FavoriteDTO> listAssociations(String userId, Date time, boolean forward, int count) {

        Page<FavoriteDO> all = listFavorites(userId, time, forward, count);
        return JpaPageResult.success(all, loanDO -> FavoriteAssembler.toDTO(loanDO));
    }

    @Override
    public PageResult<String> listAssociationIds(String userId, Date time, boolean forward, int count) {
        Page<FavoriteDO> all = listFavorites(userId, time, forward, count);
        return JpaPageResult.success(all, favoriteDO -> favoriteDO.getReferenceId());
    }

    @Override
    public Result<FavoriteDTO> get(String id) {
        FavoriteDTO favoriteDTO = FavoriteAssembler.toDTO(favoriteRepository.getOne(id));
        return Result.success(favoriteDTO);
    }

    private Page<FavoriteDO> listFavorites(String userId, Date time, boolean forward, int count) {
        Sort sort = new Sort(Sort.Direction.DESC, "gmtCreate");
        Pageable pageable = new PageRequest(0, count, sort);
        Specification<FavoriteDO> specification = Specifications.<FavoriteDO>and()
                .lt(forward && Objects.nonNull(time), "gmtCreate", time)
                .gt(!forward && Objects.nonNull(time), "gmtCreate", time)
                .eq(StringUtils.isNotBlank(userId), "userId", userId)
                .build();
        return favoriteRepository.findAll(specification, pageable);
    }
}
